package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class InterviewInterceptor implements HandlerInterceptor {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info(requestURI);
        String[] urls ={
                "/employee/login",
                "/backend/**",
                "/front/**"
        };
        //3. 判断本次请求的uri是否需要放行
        boolean flag = checkUri(urls,requestURI);
        if(flag){
            //本次请求的路径是属于不需要拦截的地址，可以直接放行
            return true;
        }

        //4. 检查是否登陆了,如果已经登陆可以直接放行
        Object employee = request.getSession().getAttribute("user");
        if(employee!=null){
            //用户已经登陆
            return true;
        }

        String resultJson = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(resultJson);
        return false;
    }

    private boolean checkUri(String[] urls, String requestURI) {
        for (String url : urls) {
            if(antPathMatcher.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
